package com.cos.lession76sb2.web.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author: COS
 * @time: 2022/10/9 14:26
 * @description:
 */
@Controller
@RequestMapping("/sys")
public class SystemController {

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
        String realPath = request.getServletContext().getRealPath("/upload");
        System.out.println(realPath);
        File file1 = new File(realPath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        file.transferTo(new File(realPath+"\\"+file.getOriginalFilename()));
        return "ok";
    }


    @RequestMapping("/download")
    public void upload(HttpServletRequest request, String name, HttpServletResponse response) throws IOException {
        String s = request.getServletContext().getRealPath("/upload") + "\\" + name;
        response.setHeader("content-disposition", "attachment;fileName="+ URLEncoder.encode(name,"utf-8" ));
        IOUtils.copy(new FileInputStream(s),response.getOutputStream());
    }
}
